package codingforgreat.class07;

public class Class03_MaxGap {
    public int maximumGap(int[] nums) {
        if (nums == null || nums.length < 2) {
            return 0;
        }
        int len = nums.length;
        int min = Integer.MAX_VALUE;
        int max = Integer.MIN_VALUE;
        for (int i = 0; i < len; i++) {
            min = Math.min(min, nums[i]);
            max = Math.max(max, nums[i]);
        }
        if (min == max) {
            return 0;
        }
        boolean[] hasNum = new boolean[len + 1];
        int[] maxs = new int[len + 1];
        int[] mins = new int[len + 1];

        for (int i = 0; i < len; i++) {
            int bid = choose(nums[i],len, min, max);
            maxs[bid] = hasNum[bid]? Math.max(maxs[bid], nums[i]): nums[i];
            mins[bid] = hasNum[bid]? Math.min(mins[bid], nums[i]): nums[i];
            hasNum[bid] = true;
        }
        int res = 0;
        int lastMax = maxs[0];
        for (int i = 1; i < len + 1; i++) {
            if (hasNum[i]) {
                res = Math.max(res, mins[i] - lastMax);
                lastMax = maxs[i];
            }
        }
        return res;
    }

    public int choose(int num,int len, int min, int max){
        double range =  (double)(max - min) / len;//桶范围
        double distance =  (double)(num - min);
        int bid = (int)(distance / range);
        return bid;
    }
}
